package com.assetmanage.controller;

import com.assetmanage.service.MinioService;
import com.assetmanage.service.impl.MinioServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/api/files")
public class FileServlet extends BaseServlet {
    private MinioService minioService = new MinioServiceImpl();

    // 获取文件列表
    public void getAllFiles(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            List<MinioService.FileInfo> files = minioService.listFiles();
            writeSuccess(resp, files);
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "获取文件列表失败：" + e.getMessage());
        }
    }

    // 上传文件
    public void uploadFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 创建文件上传处理工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 解析请求
            List<FileItem> items = upload.parseRequest(req);
            
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    // 获取文件名和内容类型
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    
                    // 获取文件输入流
                    InputStream inputStream = item.getInputStream();
                    
                    // 上传到MinIO
                    String fileUrl = minioService.uploadFile(fileName, inputStream, contentType);
                    
                    // 返回文件URL
                    writeSuccess(resp, fileUrl);
                    return;
                }
            }
            writeError(resp, "未找到上传的文件");
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "文件上传失败：" + e.getMessage());
        }
    }

    // 下载文件
    public void downloadFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileName = req.getParameter("fileName");
        if (fileName == null || fileName.isEmpty()) {
            writeError(resp, "文件名不能为空");
            return;
        }

        try {
            InputStream inputStream = minioService.downloadFile(fileName);
            // 设置响应头
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            
            // 写入响应
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                resp.getOutputStream().write(buffer, 0, bytesRead);
            }
            resp.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "文件下载失败：" + e.getMessage());
        }
    }

    // 删除文件
    public void deleteFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileName = req.getParameter("fileName");
        if (fileName == null || fileName.isEmpty()) {
            writeError(resp, "文件名不能为空");
            return;
        }

        try {
            minioService.deleteFile(fileName);
            writeSuccess(resp, null);
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "文件删除失败：" + e.getMessage());
        }
    }

    // 获取文件URL
    public void getFileUrl(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileName = req.getParameter("fileName");
        if (fileName == null || fileName.isEmpty()) {
            writeError(resp, "文件名不能为空");
            return;
        }

        try {
            String fileUrl = minioService.getFileUrl(fileName);
            writeSuccess(resp, fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            writeError(resp, "获取文件URL失败：" + e.getMessage());
        }
    }
} 